package main

import (
	"fmt"
	"log"
	"sort"
)

func threeSum(nums []int) [][]int {
	res := make([][]int, 0)
	sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
	fmt.Printf("nums: %v\n", nums)
	for i := 0; i < len(nums); i++ {
		left, right := i+1, len(nums)-1
		if nums[i] > 0 {
			break
		}
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}
		for left < right {
			sum := nums[i] + nums[left] + nums[right]
			if sum == 0 {
				res = append(res, []int{nums[i], nums[left], nums[right]})
				for left < right && nums[left] == nums[left+1] {
					left++
				}
				for left < right && nums[right] == nums[right-1] {
					right--
				}
				right--
				left++
			} else if sum > 0 {
				right--
			} else if sum < 0 {
				left++
			}
		}

	}
	return res
}
func main() {
	nums := []int{-1, 0, 1, 2, -1, -4}
	fmt.Printf("threeSum(nums): %v\n", threeSum(nums))
	log.Fatalf("return = %v", nums)
}
